
import xml.dom.minidom
from Levenshtein 	import distance
from Config 		import *
from WebService 	import *
from Debug 			import *

class Track:
	def __init__(self, node=None, album=None):
		self.name = None
		self.number = None
		if album is not None:
			self.artist = album.artist
			self.album = album.title
			self.year = album.year
		else:
			self.artist = None
			self.album = None
			self.year = None
		self.file = None
		self.new_name = None
		if node is None: return
		
		self.ID = node.getAttribute('id')
		for n in node.getElementsByTagName('title')[0].childNodes:
			if n.nodeType == n.TEXT_NODE:
				self.name = n.data.strip()
	
	def info(self):
		xml_file = WebService.get_track(self)
		document = xml.dom.minidom.parseString(xml_file.read())
		self.set_number(document.getElementsByTagName('track-list')[0])
	
	def match_file(self, files):
		min_dist = 99999
		for file in files:
			dist = distance(unicode(file), unicode(self.name)) 
			if dist < min_dist:
				min_dist = dist
				self.file = file
				
	def get_num_str(self):
		if int(self.number) < 10:
			return '0'+str(self.number)
		else:
			return str(self.number)
				
	def get_new_filename(self):
		format = Config.format_file_output()
		items = format.split(Config.SEP)
		for tag in items:
			tag = tag.strip()
			if tag == Config.ARTIST_STR:
				format = format.replace(Config.ARTIST_STR, self.artist)
			elif tag == Config.ALBUM_STR:
				format = format.replace(Config.ALBUM_STR, self.album)
			elif tag == Config.YEAR_STR:
				format = format.replace(Config.YEAR_STR, self.year)
			elif tag == Config.TRACKNUM_STR:
				format = format.replace(Config.TRACKNUM_STR, self.get_num_str())
			elif tag == Config.TRACKNAME_STR:
				format = format.replace(Config.TRACKNAME_STR, self.name)
		return format + '.mp3' 
	
	def set_number(self, node):
		self.number = str( int(node.getAttribute('offset')) + 1 )

	def set_file(self, filename):
		self.file = filename
		
	def get_new_name(self, format):
		if self.file is None:
			DEBUG('ERROR: file in track not set')
			return
		name = ''
		for tag in Config.TAGS:
			pass
		pass
	
	def __str__(self):
		s = ''
		s = s + 'Name: ' + str(self.name) + '\n'
		s = s + 'Number: ' + str(self.number) + '\n'
		s = s + 'File: ' + str(self.file) + '\n'
		s = s + 'ID: ' + str(self.ID)
		return s
